// pages/pro_detail/pro_detail.js
var common = require("../../../common/common.js").common;

var leader = require("../../../common/leader.js").leader;

var WxParse = require("../../../wxParse/wxParse.js");

var app = getApp();

var colorParse = require("../../../common/color.js");

var {$author: $author} = require("../../../components/base/authorization.js");

Page({
    /**
   * 页面的初始数据
   */
    data: {
        pagesLength: 1,
        //仅有一页，不显示返回按钮
        isIOS: false,
        swiperSite: {
            indicatorDots: true,
            autoplay: false,
            interval: 2e3,
            duration: 500
        },
        productInfo: {},
        //商品数据
        showInfoTip: false,
        //授权失败的弹框
        currentSwiper: 0,
        alert1: 0,
        current: "tab1",
        post_code: true,
        qr_code: "",
        module_name: "",
        leaderChange: false,
        //团长切换弹窗显示
        currentLeaderInfo: {},
        //当前团长信息
        modalHide: true,
        //提示框显示隐藏，true影藏
        myleaderinfo: {
            leader_id: -1
        },
        s_leader: [],
        canText: "立即购买",
        componentStyle: {
            navigationTitle: "",
            goBack: true
        }
    },
    //获取去右侧胶囊的信息
    getHeader() {
        let menuRect = wx.getMenuButtonBoundingClientRect();
        this.setData({
            topBarHeight: menuRect.height,
            topBarTop: menuRect.top
        });
    },
    /** 
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        this.getHeader();
        let pagesLength = getCurrentPages().length;
        wx.showShareMenu({
            // withShareTicket: true,
            menus: [ "shareAppMessage", "shareTimeline" ]
        });
        let that = this;
        that.setData({
            domain: app.globalData.domain.slice(0, -10),
            pagesLength: pagesLength
        });
        if (options.scene1) {
            //解析分享二维码和分享首页的数据scene
            var scene = decodeURIComponent(options.scene1);
            var s_leader = scene.split(":");
            that.setData({
                options: options,
                s_leader: s_leader,
                product_id: s_leader[3]
            });
        } else if (options.scene) {
            var scene = decodeURIComponent(options.scene);
            that.setData({
                options: options,
                product_id: scene.split("=")[1]
            });
        } else if (options.pro_id) {
            that.setData({
                product_id: options.pro_id
            });
        } else {
            wx.showModal({
                title: "提示",
                content: "暂无此商品，返回商家列表！",
                showCancel: false,
                success: function() {
                    wx.redirectTo({
                        url: "/localLifePackage/pages/businessInfo/businessInfo"
                    });
                }
            });
        }
        if (app.globalData.user) {
            //如果直接拿到openid
            that.requestStart(app.globalData.user.openid);
        } else {
            //回调拿到openid
            app.userInfoReadyCallback = (res => {
                that.requestStart(res.openid);
            });
        }
        if (options && options.onshare && options.onshare == 1) {
            that.requestStart(options.openid);
        }
        wx.getSystemInfo({
            success: function(res) {
                that.setData({
                    pixelRatio: res.pixelRatio,
                    width: res.windowWidth * (750 / res.windowWidth),
                    height: res.windowHeight * (750 / res.windowWidth)
                });
            }
        });
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    //选择团长 判断权限
    goToChooseLeader(e) {
        console.log(e);
        if (this.data.leader_change != 1) return;
        $author({
            url: e.currentTarget.dataset.url
        });
    },
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {
        const system = wx.getSystemInfoSync().system;
        const isIOS = system.includes("iOS");
        this.setData({
            isIOS: isIOS
        });
    },
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {},
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    onShareTimeline: function() {
        let that = this;
        var product_id = that.data.product_id;
        var my_leaderID = that.data.myleaderinfo.leader_id ? that.data.myleaderinfo.leader_id : "0";
        var openid = wx.getStorageSync("user").openid;
        return {
            title: that.data.productInfo.product_name,
            imageUrl: that.data.productInfo.cover,
            query: "onshare=1&openid=" + openid + "&scene1=" + encodeURIComponent("l:" + my_leaderID + ":p:" + product_id)
        };
    },
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function(res) {
        let that = this;
        var product_id = that.data.product_id;
        var my_leaderID = that.data.myleaderinfo.leader_id ? that.data.myleaderinfo.leader_id : "0";
        return {
            title: that.data.productInfo.product_name,
            imageUrl: that.data.productInfo.cover,
            path: "/localLifePackage/pages/pro_detail/pro_detail?scene1=" + encodeURIComponent("l:" + my_leaderID + ":p:" + product_id)
        };
    },
    goBack() {
        let that = this;
        let pages = getCurrentPages();
        let prevPage = pages[pages.length - 2];
        prevPage.setData({
            class_one_id: "",
            class_two_id: ""
        });
        app.globalData.link = "";
        wx.navigateBack({});
    },
    //页面请求开始
    requestStart: function(openid) {
        let that = this;
        leader.getMyLeaderInfo(openid, that.data.s_leader[1]);
        //公用方法团长请求
                that.getBase();
        //基础配置
                that.getModeName();
        //获取模块名称
                that.getProductDetail(openid);
        //获取商品详情
        },
    getClass: function() {
        let that = this;
        that.getProductDetail();
        //获取商品详情
        },
    //全局基础配置信息
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                wx.setNavigationBarTitle({
                    title: res.extra.title
                });
                wx.setNavigationBarColor({
                    frontColor: "#ffffff",
                    backgroundColor: res.extra.color_main
                });
                let wxapp_img = res.extra.wxapp_img ? res.extra.wxapp_img : "";
                if (wxapp_img.indexOf("https:") < 0) {
                    wxapp_img = wxapp_img.replace("http:", "https:");
                }
                that.setData({
                    leader_change: res.extra.l_change,
                    business_info_display: res.extra.business_info_display,
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    wxapp_img: wxapp_img,
                    leaderName: res.extra.leader_title ? res.extra.leader_title : "团长",
                    title: res.extra.title ? res.extra.title : "社区团购",
                    leader_address_on: res.extra.leader_address_on,
                    new_member_audit: res.extra.new_member_audit,
                    userAuditStatus: res.extra.userAuditStatus ? res.extra.userAuditStatus : 2
                });
            }
        });
    },
    //关闭分享弹窗的和分享
    alert_close2: function() {
        var alert1 = this.data.alert1;
        if (alert1 == 0) {
            alert1 = 1;
        } else {
            alert1 = 0;
        }
        this.setData({
            alert1: alert1
        });
    },
    swiperChange: function(e) {
        this.setData({
            currentSwiper: e.detail.current
        });
    },
    buy: function() {
        let that = this;
        wx.navigateTo({
            url: "/localLifePackage/pages/place_order/place_order?id=" + that.data.product_id
        });
    },
    getSharePoster() {
        let that = this;
        var rpx;
        wx.getSystemInfo({
            success: function(res) {
                rpx = 750 / res.windowWidth;
            }
        });
        var details = that.data.details;
        wx.showLoading({
            title: "海报生成中"
        });
        const ctx = wx.createCanvasContext("share");
        ctx.setFillStyle("#47B34F");
        ctx.fillRect(0, 0, that.data.width, that.data.height);
        // ctx.drawImage("../../images/logo.png", 188 / rpx, 38 / rpx, 80 / rpx, 80 / rpx);
        // ctx.setFillStyle('#fff');
        // ctx.font = 'normal bold 24px sans-serif';
        // ctx.fillText('社区团购', 300 / rpx, 100 / rpx);
                ctx.setFillStyle("#fff");
        ctx.fillRect(50 / rpx, 150 / rpx, (that.data.width - 100) / rpx, (that.data.height - 220) / rpx);
        ctx.setFillStyle("#434343");
        ctx.font = "normal bold 14px sans-serif";
        // ctx.fillText(that.data.productInfo.product_name, 80 / rpx, 828 / rpx);
                that.dealWords({
            ctx: ctx,
            fontSize: 14,
            FillStyle: "#434343",
            word: that.data.productInfo.product_name,
            maxWidth: 600 / rpx,
            x: 80 / rpx,
            y: 800 / rpx,
            maxLine: 2
        });
        that.dealWords({
            ctx: ctx,
            fontSize: 12,
            FillStyle: "#969696",
            word: that.data.productInfo.description,
            maxWidth: 600 / rpx,
            x: 80 / rpx,
            y: 890 / rpx,
            maxLine: 2
        });
        ctx.setFillStyle("#FE3112");
        ctx.font = "normal bold 24px sans-serif";
        ctx.fillText("￥" + that.data.productInfo.sale_price, 80 / rpx, 992 / rpx);
        var sale_price_width = ctx.measureText(that.data.productInfo.sale_price).width;
        ctx.setFillStyle("#969696");
        ctx.font = "normal bold 14px sans-serif";
        ctx.fillText("￥" + that.data.productInfo.market_price, 140 / rpx + sale_price_width, 992 / rpx);
        ctx.beginPath();
        ctx.setStrokeStyle("#dedede");
        ctx.setLineWidth(.5);
        ctx.moveTo(80 / rpx, 1040 / rpx);
        ctx.lineTo(740 / rpx, 1040 / rpx);
        ctx.stroke();
        ctx.setFillStyle("#434343");
        ctx.font = "normal bold 14px sans-serif";
        ctx.fillText("乐享本地", 308 / rpx, 1140 / rpx);
        ctx.setFillStyle("#969696");
        ctx.font = "normal bold 12px sans-serif";
        ctx.fillText("结伴而行-惬意的生活赠与惬意的你", 308 / rpx, 1180 / rpx);
        common.request({
            endpoint: "Localbusiness/common/share-code",
            method: "post",
            data: {
                product_id: that.data.product_id
            },
            success: res => {
                console.log("11" + res);
                wx.getImageInfo({
                    src: res.extra,
                    success(res) {
                        ctx.drawImage(res.path, 80 / rpx, 1060 / rpx, 200 / rpx, 200 / rpx);
                        var cover = that.data.productInfo.cover;
                        if (cover.indexOf("https:") < 0) {
                            cover = cover.replace("http:", "https:");
                        }
                        wx.getImageInfo({
                            src: that.data.productInfo.banner[0],
                            success(res) {
                                that.setData({
                                    post_code: false
                                });
                                console.log(res);
                                ctx.drawImage(res.path, 50 / rpx, 150 / rpx, 650 / rpx, 650 / rpx);
                                that.makeWxapp_img(rpx, ctx, {
                                    callback() {
                                        ctx.setFillStyle("#fff");
                                        ctx.font = "normal bold 17px sans-serif";
                                        ctx.fillText(that.data.title, 300 / rpx, 90 / rpx);
                                        ctx.draw(true, () => {
                                            wx.canvasToTempFilePath({
                                                x: 0,
                                                y: 0,
                                                width: that.data.width,
                                                height: that.data.height,
                                                destWidth: that.data.width,
                                                destHeight: that.data.height,
                                                canvasId: "share",
                                                fileType: "png",
                                                success: res => {
                                                    console.log("22");
                                                    that.setData({
                                                        post_code: true,
                                                        alert1: false
                                                    });
                                                    console.log("111" + res.tempFilePath);
                                                    let shareImage = [];
                                                    shareImage.push(res.tempFilePath);
                                                    wx.previewImage({
                                                        urls: shareImage
                                                    });
                                                    wx.hideLoading();
                                                },
                                                fail(res) {}
                                            });
                                        });
                                    }
                                });
                            }
                        });
                    }
                });
            }
        });
    },
    toBus(e) {
        wx.navigateTo({
            url: "/localLifePackage/pages/businessList/businessList"
        });
    },
    //团长切换共用方法调用
    chooseButt: function(e) {
        leader.chooseButt(e);
    },
    openMap() {
        let latitude = parseFloat(this.data.latitude);
        let longitude = parseFloat(this.data.longitude);
        wx.openLocation({
            latitude: latitude,
            longitude: longitude,
            name: this.data.myleaderinfo.title,
            address: this.data.myleaderinfo.other
        });
    },
    index_call: function(e) {
        var phone = e.currentTarget.dataset.phone;
        wx.makePhoneCall({
            phoneNumber: phone
        });
    },
    openBusinessMap() {
        let position = this.data.productInfo.business_info.position.split(",");
        console.log(position);
        console.log(this.data.productInfo.business_info);
        let latitude = parseFloat(position[1]);
        let longitude = parseFloat(position[0]);
        wx.openLocation({
            latitude: latitude,
            longitude: longitude,
            name: this.data.productInfo.business_info.name,
            address: this.data.productInfo.business_info.address
        });
    },
    getProductDetail(openid) {
        let that = this;
        common.request({
            endpoint: "Localbusiness/product/product-detail",
            method: "post",
            data: {
                product_id: that.data.product_id
            },
            header: {
                openid: openid
            },
            success: res => {
                console.log(res);
                let productInfo = res.extra;
                if (productInfo.banner) {
                    productInfo.banner = productInfo.banner.split(",");
                } else {
                    productInfo.banner = [];
                }
                if (productInfo.using_expire_in) {
                    productInfo.using_expire_in = productInfo.using_expire_in.split(",").join("~");
                }
                var canBuy;
                if (parseInt(productInfo.can_amount) > 0) {
                    canBuy = true;
                } else {
                    canBuy = false;
                    that.setData({
                        canText: "已限购"
                    });
                }
                let leader_brokerage = Number(productInfo.leader_brokerage) / 100;
                productInfo.brokerage = (productInfo.sale_price * leader_brokerage).toFixed(2);
                that.setData({
                    productInfo: productInfo,
                    month_total_sale: Number(productInfo.sale_volume) + Number(productInfo.virtual_monthly_sales),
                    canBuy: canBuy,
                    goodsDetail: WxParse.wxParse("goodsDetail", "html", productInfo.detail, that, 0)
                });
            },
            fail() {
                wx.showModal({
                    title: "提示",
                    content: "暂无此商品，返回商品列表！",
                    showCancel: false,
                    success: function() {
                        wx.redirectTo({
                            url: "/localLifePackage/pages/businessInfo/businessInfo"
                        });
                    }
                });
            }
        });
    },
    getModeName: function() {
        let that = this;
        common.request({
            endpoint: "Localbusiness/common/merchant-agreement",
            method: "post",
            data: {},
            success: res => {
                console.log(res);
                that.setData({
                    module_name: res.extra.module_name
                });
            }
        });
    },
    makeWxapp_img: function(rpx, ctx, options) {
        let that = this;
        if (that.data.wxapp_img) {
            wx.getImageInfo({
                src: that.data.wxapp_img,
                success: function(res) {
                    ctx.drawImage(res.path, 188 / rpx, 38 / rpx, 80 / rpx, 80 / rpx);
                    options.callback();
                },
                fail(res) {
                    wx.hideLoading();
                    wx.showModal({
                        title: "提示",
                        content: "图片获取失败,图片地址为" + that.data.wxapp_img,
                        showCancel: false
                    });
                }
            });
        } else {
            options.callback();
        }
    },
    //处理文字多出省略号显示
    dealWords: function(options) {
        options.ctx.setFontSize(options.fontSize);
        //设置字体大小
                options.ctx.setFillStyle(options.FillStyle);
        //设置字体颜色
                var allRow = Math.ceil(options.ctx.measureText(options.word).width / options.maxWidth);
        //实际总共能分多少行
                console.log(options);
        console.log(allRow);
        var count = allRow >= options.maxLine ? options.maxLine : allRow;
        //实际能分多少行与设置的最大显示行数比，谁小就用谁做循环次数
                var endPos = 0;
        //当前字符串的截断点
                for (var j = 0; j < count; j++) {
            var nowStr = options.word.slice(endPos);
            //当前剩余的字符串
                        var rowWid = 0;
            //每一行当前宽度    
                        if (options.ctx.measureText(nowStr).width > options.maxWidth) {
                //如果当前的字符串宽度大于最大宽度，然后开始截取
                for (var m = 0; m < nowStr.length; m++) {
                    rowWid += options.ctx.measureText(nowStr[m]).width;
                    //当前字符串总宽度
                                        if (rowWid > options.maxWidth) {
                        if (j === options.maxLine - 1) {
                            //如果是最后一行
                            options.ctx.fillText(nowStr.slice(0, m - 1) + "...", options.x, options.y + (j + 1) * 18);
                            //(j+1)*18这是每一行的高度        
                                                } else {
                            options.ctx.fillText(nowStr.slice(0, m), options.x, options.y + (j + 1) * 18);
                        }
                        endPos += m;
                        //下次截断点
                                                break;
                    }
                }
            } else {
                //如果当前的字符串宽度小于最大宽度就直接输出
                options.ctx.fillText(nowStr.slice(0), options.x, options.y + (j + 1) * 18);
            }
        }
    }
});